package cn.sjlink.user.service.impl;

import cn.sjlink.user.dao.YoshopUserMapper;
import cn.sjlink.user.entity.YoshopUser;
import cn.sjlink.user.service.UserService;
import cn.sjlink.util.*;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private final Logger logger = Logger.getLogger(getClass());
    private static final String auth_url = "https://w3.morninggo.cn/tiamoo/push/qr";
    @Autowired
    private YoshopUserMapper yoshopUserMapper;
    @Autowired
    private AccessTokenUtil accessTokenUtil;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public Result getToken(String stackId, String token)throws Exception {
        //String o = String.valueOf(redisUtil.get(token));
        String stringKey = redisUtil.getStringKey(token);
        Map<String, Object> stringObjectMap = JsonUtil.jsonToMap(stringKey);
        JSONObject jsonObject = JSONObject.parseObject(stringKey);
        String openid = (String) jsonObject.get("openid");
        YoshopUser yoshopUser = yoshopUserMapper.findByOpenId(openid);
        if(yoshopUser !=null){
            String stackToken = accessTokenUtil.getStackToken();
            //生成token
            String s = TokenUtil.MD5(stackId + yoshopUser.getUserId());
            redisUtil.set(String.valueOf(yoshopUser.getUserId()),s,86400L);
            JSONObject login = new JSONObject();
            login.put("result",200);
            login.put("userId",yoshopUser.getUserId());
            login.put("token",s);
            String encode = URLEncoder.encode(login.toJSONString(), "UTF-8");
            //todo 通知登录状态
            logger.info("deviceNo==="+stackId);
            String post = HttpClientUtil.doPostWithHeader(auth_url + "?deviceNo=" + stackId + "&jsonStr=" + encode, "", "Bearer " + stackToken);
            logger.info(post);
            if(StringUtils.isNotEmpty(post)){
                JSONObject result = JSONObject.parseObject(post);
                if((boolean)result.get("success")){
                    return new Result(true,"登录成功");
                }
                return new Result(false,"授权登录失败");
            }
            return new Result(false,"授权登录失败");
        }
        return new Result(false,"获取用户信息失败，请重新登录");
    }
}
